<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          新建销售工单
        </el-button>
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete">
          批量删除
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="20">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item label=" ">
            <el-select v-model="queryForm.sku_id" placeholder="请选择SKU" multiple style="width: 300px;" filterable>
              <el-option v-for="(item,key) in skuList" :value="item.id" :key="key"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-input v-model="queryForm.attribute" placeholder="请输入属性值" clearable/>
          </el-form-item>
          <el-form-item label=" ">
            <el-select v-model="queryForm.customer_id" placeholder="请选择下游客户" filterable clearable>
              <el-option v-for="(item,key) in customerList" :value="item.id" :key="key"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-date-picker
              clearable
              v-model="queryForm.searchDate"
              end-placeholder="下单时间-结束日期"
              format="yyyy年MM月dd日"
              start-placeholder="下单时间-开始日期"
              type="daterange"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
            <el-button icon="el-icon-refresh-left" type="success" @click="reset">
              重置
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="download">
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      @selection-change="setSelectRows"
      row-key="id"
    >
      <el-table-column align="center" show-overflow-tooltip type="selection"/>
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ total - (queryForm.pageNo - 1) * queryForm.pageSize - $index }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="销售工单"
        prop="label"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="销售日期"
        prop="sale_date"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="SKU"
        prop="sku.label"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="销售数量"
        prop="number"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="计价单位"
        prop="unit"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="销售单价(￥)"
        prop="unit_price"
        show-overflow-tooltip
      >
        <template #default="{row}">
          {{new Intl.NumberFormat('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        }).format(row.unit_price)}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="销售金额(￥)"
        prop="unit_price"
        show-overflow-tooltip
      >
        <template #default="{row}">
          {{new Intl.NumberFormat('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        }).format(row.total_price)}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="单位KWH"
        prop="unit_kwh"
        show-overflow-tooltip
      >
        <template #default="{row}">{{ row.unit_kwh }}</template>
      </el-table-column>
      <el-table-column
        align="center"
        label="总KWH"
        prop="total_kwh"
        show-overflow-tooltip
      >
        <template #default="{row}">{{ row.total_kwh }}</template>
      </el-table-column>
      <el-table-column
        align="center"
        label="KWH单价(￥)"
        prop="kwh_unit_price"
        show-overflow-tooltip
      >
        <template #default="{row}"> {{ row.kwh_unit_price }}</template>
      </el-table-column>
      <el-table-column
        align="center"
        label="下游客户"
        prop="customer.label"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="备注"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="操作"
        show-overflow-tooltip
        width="200"
      >
        <template #default="{ row }">
          <el-button circle icon="el-icon-view" @click="handleShow(row)" type="success"/>
          <el-button circle icon="el-icon-edit" @click="handleEdit(row)" type="primary"/>
          <el-button circle icon="el-icon-delete" @click="handleDelete(row)" type="danger"/>
          <el-button circle icon="el-icon-download" @click="handleDownload(row)" type="warning" v-if="row.file_path"/>
        </template>
      </el-table-column>

      <template #empty>
        <el-image
          class="vab-data-empty"
          :src="require('@/assets/empty_images/data_empty.png')"
        />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" :customer-list="customerList" :sku-list="skuList"/>
    <el-image-viewer v-if="imgPreviewVisible" :url-list="imgSrc" :on-close="imgPreviewClose"/>
  </div>
</template>

<script>
import {attr as getSkuList} from '@/api/sku/classify'
import {getList as getCustomerList} from '@/api/business/customer'
import {doDelete, getList, downloadExcel} from '@/api/order/orderProduct'
import {save as exportMissionSave} from '@/api/order/exportMission'
import edit from './components/orderProEdit'
import ElImageViewer from "element-ui/packages/image/src/image-viewer";

export default {
  watch: {
    '$route'(to, from) {
      // 路由变化时重新加载数据
      if (to.path === '/orderProManagement') {
      // 路由变化为当前页时重新加载数据
      this.getFilter();
    }
    }
  },
  name: 'orderProductManagement',
  components: {ElImageViewer, edit},
  filters: {},
  data() {
    return {
      statusMap: {},
      skuList: [],
      customerList: [],
      list: [],
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      queryForm: {
        searchDate: [
          '',
          ''
        ],
        pageNo: 1,
        pageSize: 10,
        fromTime: '',
        toTime: ''
      },
      imgSrc: [],
      imgPreviewVisible: 0,
      fileRootPath: '',
      area: ''
    }
  },
  created() {
    this.fileRootPath = process.env.VUE_APP_FILE_ROOT_PATH
    this.fetchData()
    this.getFilter()

  },
  methods: {
    handleDownload(row) {
      // 获取文件路径
      const filePath = this.fileRootPath + row.file_path;

      // 创建一个隐藏的 <a> 标签
      const link = document.createElement("a");

      // 设置 href 和 download 属性
      link.href = filePath;
      link.download = row.file_name || "default_filename"; // 如果有文件名就用文件名，否则用默认值

      // 将 <a> 标签添加到文档中
      document.body.appendChild(link);

      // 触发点击事件以下载文件
      link.click();

      // 移除 <a> 标签
      document.body.removeChild(link);
    },
    setSelectRows(val) {
      this.selectRows = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.pageNo = 1
      this.fetchData()
    },
    imgPreview(event) {
      var el = event.currentTarget
      this.imgPreviewVisible = 1
      this.imgSrc.push(el.src)
    },
    imgPreviewClose() {
      this.imgPreviewVisible = 0
      this.imgSrc.pop()
    },
    async fetchData() {
      if (!this.queryForm.searchDate) {
        this.queryForm.searchDate = []
      }
      this.queryForm.fromTime = this.queryForm.searchDate[0]
      this.queryForm.toTime = this.queryForm.searchDate[1]
      this.listLoading = true
      const {
        data: {list, total, area},
      } = await getList(this.queryForm)
      this.list = list
      this.total = total
      this.area = area
      this.listLoading = false
    },
    async getFilter() {
      getSkuList({pageNo: 'all'}).then(response => {
        this.skuList = response.data.list
      });
      getCustomerList({pageNo: 'all','relationship':2}).then(response => {
        this.customerList = response.data.list
      });
    },
    toView(row) {
      this.$router.push({path: '/orderView', query: {id: row.id}})
    },
    reset() {
      this.queryForm.searchDate = ['', '']
      this.queryForm.fromTime = ''
      this.queryForm.toTime = ''
      this.queryForm.sku_id = []
      this.queryForm.customer_id = ''
      this.queryForm.attribute = ''
    },
    download() {
      if (this.queryForm.searchDate == null) {
        this.queryForm.searchDate = ['', '']
      }
      this.queryForm.fromTime = (this.queryForm.searchDate[0]) ?? ''
      this.queryForm.toTime = (this.queryForm.searchDate[1]) ?? ''
      if (this.total <= 10000) {
        this.$baseMessage('正在导出请耐心等待', 'success', 'vab-hey-message-success')
        // const Qs = require('qs');
        // window.location.href = process.env.VUE_APP_BASE_URL + '/admin/Express/excel?area='+this.area + '&' + Qs.stringify(this.queryForm)
        downloadExcel(this.queryForm).then(res => {
          const link = document.createElement("a");
          let blob = new Blob([res], {type: "application/vnd.ms-excel"});
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", '产品销售工单');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
      } else {
        this.queryForm.title = '订单列表'
        exportMissionSave(this.queryForm).then((data) => {
          this.$baseMessage(data.msg, 'success', 'vab-hey-message-success')
        })
      }
    },
    handleEdit(row) {
      if (row.id) {
        this.$refs['edit'].showEdit(row)
      } else {
        this.$refs['edit'].showEdit(null)
      }
    },
    handleShow(row) {
      this.$refs['edit'].viewEdit(row)
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const {msg} = await doDelete({ids: row.id})
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          await this.fetchData()
        })
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join()
          this.$baseConfirm('你确定要删除选中项吗', null, async () => {
            const {msg} = await doDelete({ids})
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
        }
      }
    },

  },
}
</script>
<style lang="scss" scoped>
.list-container {
  ul {
    padding: 0;
    margin: 0;
    list-style: none;
    outline: none;

    .list-item {
      padding: $base-padding;
      //border-bottom: 1px solid $base-border-color;

      &-meta {
        display: flex;
        flex: 1 1;
        align-items: flex-start;

        &-avatar {
          margin-right: 16px;

          ::v-deep {
            .el-image {
              width: 61px;
              height: 61px;
            }
          }
        }

        &-content {
          flex: 1 0;
          width: 0;
          color: rgba(0, 0, 0, 0.85);
        }

        &-title {
          margin-top: 11px;
          margin-bottom: 4px;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.85);
        }

        &-description {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
        }

        &-item {
          display: inline-block;
          height: 61px;
          margin-left: 40px;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
          vertical-align: middle;

          > span {
            line-height: 30px;
          }

          > p {
            margin-top: 4px;
            margin-bottom: 0;
          }
        }

        ::v-deep {
          .el-progress {
            margin-top: 21px;
          }
        }
      }
    }
  }
}
</style>
